
clear all
set more off, perm
set mem 10000000
set matsize 10000
version 13

cd "$sens"

** Script to calculate average outcomes of neighboring (non-sample) villages

use "panel_for_ngh_outcomes.dta", clear
local N = _N
count if fs_sample_150==1
local N_sample = r(N)
cap drop *_ngh*
drop if centroid_y==. | centroid_x==.

*Create empty variables for brightness of neighboring villages (within varying radii)
local ngh_list = "lights_max2001_hat lights_max2011_hat diff_max_proj_01_11 work_pooled_ag_?_?? work_pooled_ot_?_??"
foreach v of varlist `ngh_list' {
  foreach k in 10 20 50 {
    gen `v'_ngh`k' = .  
  }	
}

*Identify non-sample neighbors of sample villages, and calculate average brightness
forvalues i = 1/`N' {
  if fs_sample_150[`i']==1 {
    local lat = centroid_y[`i']
    local lon = centroid_x[`i']
    qui geodist `lat' `lon' centroid_y centroid_x, gen(dist_temp)
    foreach v of varlist `ngh_list' {
      foreach k in 10 20 50 {
        qui sum `v' if dist_temp<=`k' & fs_sample_150==0  // include only villages within k radius that AREN'T in the RD sample!
        cap replace `v'_ngh`k' = r(mean) if _n==`i'  // for village i, assign average brightness of neighbors
      }	  
    }
    drop dist_temp
    local N_sample = `N_sample'-1
    di "`i' (`N_sample' remaining)"
  }
}

*Save results
compress
save "panel_ngh_outcomes.dta", replace
